import Vue from 'vue'
import axios from 'axios'
import QS from 'qs'

//自动切换环境
if (process.env.NODE_ENV == 'development') {
  axios.defaults.baseURL = '/api'
} else if (process.env.NODE_ENV == 'debug') {
  axios.defaults.baseURL = '/api'
} else if (process.env.NODE_ENV == 'production') {
  axios.defaults.baseURL = 'http://***********/'
}

axios.defaults.headers.post['content-Type'] = 'application/json;charset=UTF-8';
//定义计时器
// loading框设置局部刷新，且所有请求完成后关闭loading框
let loading
let needLoadingRequestCount = 0 // 声明一个对象用于存储请求个数

function startLoading () {
  loading = Vue.prototype.$loading({
    lock: true,
    text: '努力加载中...',
    background: 'rgba(0,0,0,0.5)',
    target: document.querySelector('.loading-area') // 设置加载动画区域
  })
}

function endLoading () {
  loading.close()
}

function showFullScreenLoading () {
  if (needLoadingRequestCount === 0) {
    startLoading()
  }
  needLoadingRequestCount++
}

function hideFullScreenLoading () {
  if (needLoadingRequestCount <= 0) return
  needLoadingRequestCount--
  if (needLoadingRequestCount === 0) {
    endLoading()
  }
}

// http请求拦截器
axios.interceptors.request.use(config => {
  if (config.isLoading !== false) { // 如果配置了isLoading: false，则不显示loading
    showFullScreenLoading()
  }
  config.headers['Content-Type'] = 'application/json;charset=UTF-8'
  return config
}, error => {
  hideFullScreenLoading()
  return Promise.reject(error.response)
})

// http响应拦截器
axios.interceptors.response.use(data => {
  hideFullScreenLoading() // 响应成功关闭loading
  return data
}, error => {
  setTimeout(function(){
    hideFullScreenLoading()
  },5000)
  
  let _status = error.response && error.response.status
  if (_status === 504 || _status === 404) {
    // 跳转404页面（目前没有，只能先跳转首页）
    //router.push({ path: '/' })
  }
  return Promise.reject(error)
})



// 自定义判断元素类型JS
function toType (obj) {
  return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase()
}
/** 参数过滤函数*/
function filterNull (o) {
  for (var key in o) {
    if (o[key] === null) {
      delete o[key]
    }
    if (toType(o[key]) === 'string') {
      o[key] = o[key].trim()
    } else if (toType(o[key]) === 'object') {
      o[key] = filterNull(o[key])
    } else if (toType(o[key]) === 'array') {
      o[key] = filterNull(o[key])
    }
  }
  return o
}
/**添加headers,可以动态添加header参数*/
function setHeaders(headers){
  axios.defaults.headers.school_id = headers.school_id;
  axios.defaults.headers.token = headers.token;
}


function apiAxios (method, url,headers, params, success, failure) {
  if (headers){
    headers = filterNull(headers);
    setHeaders(headers)
  }
 
  if (params) {
    params = filterNull(params)
  }
  axios({
    method: method,
    url: url,
    data: method === 'POST' || method === 'PUT' ? params : null,
    params: method === 'GET' || method === 'DELETE' ? params : null,
    withCredentials: false
  }).then(function (res) {
    if (res.data.error_code === 1000) {
      if (success) {
    //使用success(data)方法
        success(res.data)
      }
    } else {
      failure(res.data)
    }
  }).catch(function (err) {
    let res = err.response
    if (err) {
      window.alert('api error, HTTP CODE: ' + res.status)
    }
  })
}
 
// 返回在vue模板中的调用接口
export default {
  get: function (url,headers, params, success, failure) {
    return apiAxios('GET', url,headers, params, success, failure)
  },
  post: function (url,headers, params, success, failure) {
    return apiAxios('POST', url,headers, params, success, failure)
  },
  put: function (url,headers, params, success, failure) {
    return apiAxios('PUT', url,headers, params, success, failure)
  },
  delete: function (url,headers, params, success, failure) {
    return apiAxios('DELETE', url,headers, params, success, failure)
  }
}